home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 258 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  83 lines

  1. Path: gate.net!pslfl2-24
  2. From: bhutto@gate.net (William Hutto)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Pointers to structures
  5. Date: 3 Jan 1996 21:08:43 GMT
  6. Organization: CyberGate, Inc.
  7. Message-ID: <4cer8r$1v44@news.gate.net>
  8. References: <4cc9r4$m26@armitage.cyberspace.com> <4ccpgv$qpl@ixnews8.ix.netcom.com>
  9. NNTP-Posting-Host: pslfl2-24.gate.net
  10. X-Newsreader: News Xpress Version 1.0 Beta #4
  11.  
  12. icarus@loomis (Tel Janin Aellinsar) wrote:
  13.  
  14. >Berserker Dragon, Knights of the Cosmos             icarus@BERKSHIRE.NET
  15.  
  16. > I'm having trouble using a pointer to a struct.  The idea is to
  17. > have a struct get filled by a function, which gets the address
  18. > and everything via function(struct type*).  Very straightforward.
  19. > However, if I try to CHANGE anything in the struct, it just goes
  20. > back when the function is over.  So, let's pretend this imaginary
  21. > structure is what I'm using:
  22. >
  23. > struct st1 {
  24. >   char *name;
  25. >   int yadda;
  26. > };
  27. >
  28. > And the function is:
  29. >
  30. > fn1(struct st1 *st)
  31.  
  32. If you want to assigned values to be retained, this needs to be double 
  33. indirection.
  34.  
  35.     void fn1(struct st1 **st)
  36.  
  37. > {
  38. >   st = (struct st1*)malloc(sizeof(struct st1*));
  39.                                     ^^^^^^^^^^^
  40. This allocates enough space for a pointer, not your structure. Nor does it 
  41. check validity before usage. This should be:
  42.  
  43.     if((*st=malloc(sizeof(struct st1))==NULL) {
  44.         /*error*/
  45.     }        
  46.  
  47. Also note the indirection: *st
  48.  
  49. st points to the pointer that you pass to this function. That's where 
  50. malloc()'s returned value is going.
  51.  
  52. >   st->name = (char*)malloc(16);
  53.  
  54.     if((*st->name=malloc(16))==NULL) {
  55.         /*error*/
  56.     }
  57.  
  58. >   strcpy(st->name,"Test");
  59.  
  60.     strcpy(*st->name,"Test");
  61.  
  62. >   st->yadda = 100;
  63.  
  64.     *st->yadda = 100;
  65.  
  66. > }
  67.  
  68. You must call this function with the address of a pointer of struct type.
  69.  
  70. func()
  71. {
  72. struct st1 *stptr;
  73.  
  74.     fn1(&stptr);
  75.     printf("%s, %d\n",stptr->name,stptr->yadda);
  76.     
  77. }                
  78.  
  79. Hope that helps,
  80. Bill
  81.  
  82. "Whatcha got on?...Your mind?"
  83.